package cn.itrip.trade.controller;

import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.dto.Dto;
import cn.itrip.pojo.ItripHotelOrder;
import cn.itrip.trade.config.WXPayConfig;
import cn.itrip.trade.service.ItripHoptelOrderService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/wxpay")
public class WxPaymentController {

    @Resource
    private ItripHoptelOrderService itripHoptelOrderService;

    @Resource
    private WXPayConfig config;

    /**
     * 统一下单
     * @param orderNo
     * @return
     */
    @RequestMapping(value="/createqccode/{orderNo}",method = RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Map<String,Object>> prePay(@PathVariable String orderNo){
        try {
            WXPay wxpay = new WXPay(config);
            ItripHotelOrder order = itripHoptelOrderService.getHotelOrderByOrderNo(orderNo);
            Map<String, String> data = new HashMap<String, String>();
            //商品描述
            data.put("body", "爱旅行微信支付模块");

            //订单编号
            data.put("out_trade_no", orderNo);
            //标价币种      符合ISO 4217标准的三位字母代码，默认人民币：CNY，
            data.put("fee_type", "CNY");

            //以下字段在return_code为success的时候有返回
            //设备号
            data.put("device_info", "");

            //设置的金额（以分为单位）
            data.put("total_fee", "1");
            data.put("spbill_create_ip", "123.12.12.123");
            //回调地址
            data.put("notify_url", config.getNotifyUrl());
            // 此处指定为扫码支付  为交易类型
            data.put("trade_type", "NATIVE");
            //产品id（房间id） 预支付交易会话标识
            data.put("product_id",order.getRoomId().toString() );

            Map<String, String> resp = wxpay.unifiedOrder(data);

            if(WXPayConstants.SUCCESS.equals(resp.get("return_code"))){
                if(WXPayConstants.SUCCESS.equals(resp.get("result_code"))){

                    Map<String,Object> param = new HashMap<>();
                    param.put("orderNo",orderNo);
                    param.put("hotelName",order.getHotelName());
                    param.put("payAmount","1");
                    param.put("roomId",order.getRoomId());
                    param.put("count",order.getCount());
                    param.put("codeUrl",resp.get("code_url"));

                    return DtoUtil.returnDataSuccess(param);
                }else{
                    return DtoUtil.returnFail("订单支付失败","100001");
                }
            }else{
                return DtoUtil.returnFail("订单支付失败","100001");
            }
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("订单支付失败","100001");
        }
    }

    /**
     * 微信异步回调接口
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/notify",method = RequestMethod.POST)
    public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws Exception{
        try {
            InputStream inputStream = request.getInputStream();//获取字节流
            //将字节流转换成高级缓冲流
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            String s = null;
            StringBuilder sb = new StringBuilder();
            while ((s=reader.readLine()) != null){
                sb.append(s);
            }
            reader.close();
            inputStream.close();

            //将结果转化为xml格式的数据
            Map<String, String> result = WXPayUtil.xmlToMap(sb.toString());
            System.out.println("result============"+result);

            //通过获取的结果去进行业务逻辑操作
            WXPay wxPay = new WXPay(config);
            //验签
            //boolean flag = wxPay.isPayResultNotifySignatureValid();
            boolean flag = wxPay.isResponseSignatureValid(result);

            //验证成功
            if(flag){
                //获取结果
                String returnCode = result.get("return_code");
                if(WXPayConstants.SUCCESS.equals(returnCode)){
                    String resultCode = result.get("result_code");
                    if(WXPayConstants.SUCCESS.equals(resultCode)){
                        String orderNo = result.get("out_trade_no");
                        ItripHotelOrder order = itripHoptelOrderService.getHotelOrderByOrderNo(orderNo);
                        if(EmptyUtils.isNotEmpty(order) && EmptyUtils.isEmpty(order.getTradeNo())){
                            //金额的判断  上面金额已写死
                            if(Integer.parseInt(result.get("total_fee")) == 1){
                                //订单的修改
                                order.setPayType(2);
                                //微信支付
                                order.setTradeNo(result.get("transaction_id"));
                                order.setOrderStatus(2);
                                //支付成功
                                itripHoptelOrderService.updateOrderStatus(order);

                                //返回信息给微信平台
                                Map<String,String> param = new HashMap<>();
                                param.put("return_code","SUCCESS");
                                param.put("return_msg","OK");
                                String mapToXml = WXPayUtil.mapToXml(param);

                                //输出
                                response.setContentType("application/xml;charset=utf-8");
                                PrintWriter out = response.getWriter();
                                out.println(mapToXml);
                                out.flush();
                                out.close();

                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 定单刷新的接口
     * @param orderNo
     * @return
     */
    @RequestMapping(value="/queryorderstatus/{orderNo}",method = RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto queryOrderStatus(@PathVariable String orderNo,HttpServletResponse response){
        try {
            if(EmptyUtils.isEmpty(orderNo)){
                return DtoUtil.returnFail("订单编号不能为空","100002");
            }
            ItripHotelOrder order = itripHoptelOrderService.getHotelOrderByOrderNo(orderNo);
            if (EmptyUtils.isEmpty(order)){
                return DtoUtil.returnFail("订单不存在","100002");
            }
//
//            //返回信息给微信平台
//            Map<String,String> param = new HashMap<>();
//            param.put("return_code","SUCCESS");
//            param.put("return_msg","OK");
//            String mapToXml = WXPayUtil.mapToXml(param);
//            //输出
//            response.setContentType("application/xml;charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.println(mapToXml);
//            out.flush();
//            out.close();

            return DtoUtil.returnDataSuccess(order);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("订单刷新失败","100002");
        }
    }
}
